<template>
    <view style="display: flex;flex-wrap: wrap;">
		<view class="GoodsCard" >
			<view style="display: flex;">
				<!-- 左图 -->
				<view class="left" @click="goToProductDetail">
					<view class="img">
						<img :src="displayImg" class="img">
					</view>
				</view>
				<!-- 右文 -->
				<view class="right">
					<view class="info-item">
						<view class="info-item-title product-name" @click="goToProductDetail">
							{{displayName}}
                            <!-- 子组件渲染方式:{{  }} -->
						</view>
					</view>
					<view class="info-item">
						<view class="info-item-title">
							{{displayDescribe}}
						</view>
					</view>
					<view class="info-item" style="color: #ff5000;">
						<view class="info-item-title">
							¥{{displayPrice}}
						</view>
                        <view class="info-item-title">
                            库存:{{currentMargin}}份
                        </view>
					</view>
					<view class="info-item">
						<view class="quantity-selector">
							<view class="quantity-label">数量：</view>
							<view class="quantity-controls">
								<button class="quantity-btn" @click="decreaseQuantity" :disabled="quantity <= 1">-</button>
								<input 
									type="number" 
									v-model="quantity" 
									class="quantity-input" 
									min="1" 
									:max="currentMargin"
									@change="validateQuantity"
								/>
								<button class="quantity-btn" @click="increaseQuantity" :disabled="quantity >= currentMargin">+</button>
							</view>
						</view>
						<view class="infobutton" @click="shoppingok">
							<slot>加入购物车</slot>
						</view>
					</view>
				</view>
				
			</view>
		</view>
		
	</view>
</template>

<script>
import { computed } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';

export default{
    setup(props){
        const store = useStore();
        const router = useRouter();
        
        // 使用Vuex获取数据
        const mycollection = computed(() => store.getters.cartItems);
        const Movies = computed(() => store.getters.allProducts);
        
        return {mycollection, Movies, router, store}
    },
    data(){
        return {
            quantity:1,
        }
    },
    computed:{
       // 从 Vuex store 获取完整的商品信息（优先使用 store 中的数据）
       productFromStore() {
            const allProducts = this.$store.getters.allProducts;
            return allProducts.find(item => item.id === this.id);
        },
        
        // 商品名称：优先使用 store 中的数据
        displayName() {
            return this.productFromStore ? this.productFromStore.name : this.name;
        },
        
        // 商品价格：优先使用 store 中的数据
        displayPrice() {
            return this.productFromStore ? this.productFromStore.price : this.price;
        },
        
        // 商品描述：优先使用 store 中的数据
        displayDescribe() {
            return this.productFromStore ? this.productFromStore.describe : this.describe;
        },
        
        // 商品图片：优先使用 store 中的数据
        displayImg() {
            return this.productFromStore ? this.productFromStore.img : this.img;
        },
        
        // 获取最新的库存信息（优先使用 store 中的数据）
        currentMargin() {
            return this.productFromStore ? this.productFromStore.margin : this.margin;
        }
    },
    // props用法分为三步：1父组件传值 2子组件通过props接收 3子组件渲染
    props:{
        id:{
            type:Number,
            default:'商品编号'
        },
        name:{
            type:String,
            default:'商品名称'
        },
        price:{
            type:Number,
            default:99999
        },
        describe:{
            type:String,
            default:'商品描述'
        },
        img:{
            type:String,
            default:'../public/favicon.ico'
        },
        margin:{
            type:Number,
            default:0
        },
        // 是否选中
        selected:{
            type:Boolean,
            default:false

        }
    },
    methods:{
        // 选购加1
        increaseQuantity(){
            if(this.quantity < this.currentMargin){
                this.quantity++;
            }
        },
        // 减少1
        decreaseQuantity(){
            if(this.quantity >1) {
                this.quantity--;
            }
        },
        //输入数量验证
        validateQuantity(){
            // 如果小于1，设置为1
            if(this.quantity<1){
                this.quantity=1;
            }else if(this.quantity>this.currentMargin){
                this.quantity=this.currentMargin;
                alert(`库存不足，最多只能选择${this.currentMargin}件`);
            }
        },
        async shoppingok(){
            // 验证数量
            if(this.quantity<1){
                alert('请选择至少1件商品');
                return;
            }
            if(this.quantity>this.currentMargin){
                alert(`库存不足，最多只能选择${this.currentMargin}件`);
                return;
            }
            // 从 store 获取最新的商品信息
            const allProducts = this.$store.getters.allProducts;
            const productInfo = allProducts.find(item => item.id === this.id) || {
                name: this.displayName,
                describe: this.displayDescribe,
                price: this.displayPrice,
                img: this.displayImg
            };
            
            // 打包给后端数据库的数据对象，要验证通过才能记录表格
            let goodobj = {
				  id: 0,
				  goodid: this.id,
				  title: productInfo.name,
				  mydescribe: productInfo.describe,
				  price: productInfo.price,
				  num: this.quantity,
				  img: productInfo.img,
				  memo: '',
				  clicknum: 0,
				  goodtype: '',
				  createBy: this.$store.state.loginName,
				  remark: '',
				  status: '未提交'
				};
                //提交到数据库
                this.execdata('/system/cart', goodobj).then(response => {
					 console.log('添加成功：', goodobj);
                     alert('添加成功');
				});

            try {
                // 使用Vuex action添加商品到购物车（使用 store 中的最新数据）
                const product = {
                    id: this.id,
                    name: productInfo.name,
                    price: productInfo.price,
                    describe: productInfo.describe,
                    img: productInfo.img,
                    num: this.quantity
                };
                
                await this.$store.dispatch('addToCart', product);
                const updatedProducts = this.$store.getters.allProducts;
                const updatedProduct = updatedProducts.find(item => item.id === this.id);
                if (updatedProduct) {
                    alert(`${productInfo.name}成功加入购物车 ${this.quantity} 件商品，剩余库存：${updatedProduct.margin} 件`);
                } else {
                    alert(`${productInfo.name}成功加入购物车 ${this.quantity} 件商品`);
                }
            } catch (error) {
                alert(error.message);
            }
        },

        // 跳转到商品详情页
        goToProductDetail() {
            this.router.push(`/product/${this.id}`);
        }
    }
}
</script>

<style scoped>
/* 商品卡片整体 */
.GoodsCard {
    width: 100%;
    max-width: 400px;
    margin: 10px;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
    background: #fff;
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    font-family: 'Helvetica Neue', Arial, sans-serif;
    cursor: pointer;
}

.GoodsCard:hover {
    transform: translateY(-5px);
    box-shadow: 0 15px 30px rgba(0, 0, 0, 0.15);
}

/* 左右布局 */
.GoodsCard > view {
    display: flex;
}

/* 左侧图片 */
.left {
    flex: 1;
    padding: 10px;
}

.img {
    width: 120px;
    height: 120px;
    border-radius: 12px;
    object-fit: cover;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
}
.img img {
    width: 100%;
    height: 100%;
    border-radius: 12px;
}

/* 右侧文字区域 - 核心样式 */
.right {
    flex: 2;
    padding: 15px 10px 10px 0;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.info-item {
    margin-bottom: 8px;
    line-height: 1.4;
}

.info-item-title {
    font-size: 15px;
    color: #333;
    font-weight: 500;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* 商品名称 */
.info-item:nth-child(1) .info-item-title {
    font-size: 16px;
    font-weight: 600;
    color: #1a1a1a;
}

/* 描述 */
.info-item:nth-child(2) .info-item-title {
    font-size: 14px;
    color: #666;
    font-weight: 400;
}

/* 价格 */
.info-item:nth-child(3) .info-item-title {
    font-size: 18px;
    font-weight: 700;
    color: #ff5000;
}

/* 库存/数量 */
.info-item:nth-child(4) .info-item-title {
    font-size: 13px;
    color: #999;
}

/* 加入购物车按钮 */
.infobutton {
    margin-top: 6px;
    padding: 8px 14px;
    background: #ff5000;
    color: white;
    font-size: 14px;
    font-weight: 600;
    border-radius: 20px;
    text-align: center;
    cursor: pointer;
    transition: background 0.3s ease;
    box-shadow: 0 2px 6px rgba(255, 80, 0, 0.3);
}

.infobutton:hover {
    background: #e64900;
}

/* 数量选择器样式 */
.quantity-selector {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 10px;
}

.quantity-label {
    font-size: 14px;
    color: #666;
    font-weight: 500;
}

.quantity-controls {
    display: flex;
    align-items: center;
    border: 1px solid #e1e8ed;
    border-radius: 8px;
    overflow: hidden;
    background: white;
}

.quantity-btn {
    width: 32px;
    height: 32px;
    border: none;
    background: #f8f9fa;
    color: #333;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    justify-content: center;
}

.quantity-btn:hover:not(:disabled) {
    background: #667eea;
    color: white;
}

.quantity-btn:disabled {
    background: #f0f0f0;
    color: #ccc;
    cursor: not-allowed;
}

.quantity-input {
    width: 60px;
    height: 32px;
    border: none;
    text-align: center;
    font-size: 14px;
    font-weight: 500;
    color: #333;
    background: white;
    outline: none;
}

.quantity-input:focus {
    background: #f8f9fa;
}

/* 响应式：小屏适配 */
@media (max-width: 480px) {
    .GoodsCard {
        max-width: 100%;
        margin: 8px 0;
    }
    .right {
        padding: 12px 8px 8px 0;
    }
    .info-item-title {
        font-size: 14px;
    }
    .img {
        width: 100px;
        height: 100px;
    }
    
    .quantity-selector {
        flex-direction: column;
        align-items: flex-start;
        gap: 5px;
    }
    
    .quantity-controls {
        width: 100%;
    }
    
    .quantity-input {
        width: 80px;
    }
}

/* 可点击的商品名称 */
.product-name {
    cursor: pointer;
    transition: color 0.3s ease;
}

.product-name:hover {
    color: #667eea;
    text-decoration: underline;
}
</style>